import { defineStore } from "pinia";
import type { ConfigCol, StoreTable } from "@/utils/struct";
import { useConfigTableStore } from "@/stores/config/configTableStore";
import { ConfigDataType } from "@/utils/enum";
const electron = require("electron")

export const createTablePageStore = (storeId:string)=>{
    return defineStore(storeId, {
        state: () => ({
            selectedId: 0,
            selectedRowId: 0
        }),
        getters: {
            selectedTable(): StoreTable|undefined {
                let tableStore = useConfigTableStore()
                return tableStore.getTable(this.selectedId)
            }
        },
        actions: {
            addCurTableRow() {
                let curTable= this.selectedTable
                if (!curTable) {
                    return
                }
                let rowId = curTable.nextRowId
                curTable.rows.push({
                    id:rowId,
                    values: new Array(curTable.tableHeader.length).fill(0)
                })
                curTable.nextRowId++
                electron.ipcRenderer.send("addTableRow", curTable.id, rowId)
            },
            deleteCurTableRow(idx: number) {
                let table = this.selectedTable
                if (!table) {
                    return
                }
                let rowId = table.rows[idx].id
                table.rows.splice(idx, 1)
                electron.ipcRenderer.send("deleteTableRow", table.id, rowId)
            },
            addCurTableCol(col: ConfigCol) {
                let table = this.selectedTable
                if (!table) {
                    return
                }
                let header = {id: table.nextHeaderId++, key:col.key, label: col.name, type:col.type, quoteId:0, exportGroups:[]}
                if (col.type == ConfigDataType.Quote) {
                    header.quoteId = col.id
                }
                table.tableHeader.push(header)
                for (let i = 0; i < table.rows.length; i++) {
                    table.rows[i].values.push(0)
                }
                electron.ipcRenderer.send("addTableCol", table.id, header)
            },
            deleteCurTableCol(id:number) {
                let table = this.selectedTable
                if (!table) {
                    return
                }
                let idx = table.tableHeader.findIndex(x=>x.id == id)
                table.tableHeader.splice(idx, 1)
                for (let i = 0; i < table.rows.length; i++) {
                    table.rows[i].values.splice(idx, 1)
                }
                electron.ipcRenderer.send('deleteTableCol', table.id, id)
            }
        }
    })
}
export const useTablePageStore = createTablePageStore('tablePageStore')
export const useTableSelectPageStore = createTablePageStore('tableSelectPageStore')